package com.blrs.service.enterprise.records.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.blrs.common.core.domain.entity.SysUser;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.BusinessFollowAnnotater;
import com.blrs.domain.BusinessOpportunityInformation;
import com.blrs.mapper.BusinessFollowAnnotaterMapper;
import com.blrs.mapper.BusinessOpportunityInformationMapper;
import com.blrs.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.mapper.BusinessFollowRecordsMapper;
import com.blrs.domain.BusinessFollowRecords;
import com.blrs.service.enterprise.records.IBusinessFollowRecordsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商机跟进记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-25
 */
@Service
public class BusinessFollowRecordsServiceImpl implements IBusinessFollowRecordsService 
{
    @Autowired
    private BusinessFollowRecordsMapper businessFollowRecordsMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private BusinessOpportunityInformationMapper businessOpportunityInformationMapper;
    @Autowired
    private BusinessFollowAnnotaterMapper businessFollowAnnotaterMapper;

    /**
     * 查询商机跟进记录
     * 
     * @param recordsId 商机跟进记录主键
     * @return 商机跟进记录
     */
    @Override
    public BusinessFollowRecords selectBusinessFollowRecordsByRecordsId(String recordsId)
    {
        BusinessFollowRecords businessFollowRecords = businessFollowRecordsMapper.selectBusinessFollowRecordsByRecordsId(recordsId);
            if(StringUtils.isNotEmpty(businessFollowRecords.getAnnotationsUserId())){
                List<SysUser> sysUsers=new ArrayList<>();
                String[] strings = businessFollowRecords.getAnnotationsUserId().split(",");
                for (String s:strings) {
                    Long aLong = Long.parseLong(s);
                    SysUser e = sysUserMapper.selectUserById(aLong);
                    sysUsers.add(e);
                }
                businessFollowRecords.setSysUser(sysUsers);
        }
        BusinessFollowAnnotater businessFollowAnnotater = businessFollowAnnotaterMapper.selectBusinessFollowRecordsByRecordsIdAndUserId(businessFollowRecords.getRecordsId(), SecurityUtils.getUserId());
            if (Objects.nonNull(businessFollowAnnotater) && Objects.nonNull(businessFollowAnnotater.getAnnotaterDetail())){
                businessFollowRecords.setAnnotations(businessFollowAnnotater.getAnnotaterDetail());
            }else {
                businessFollowRecords.setAnnotations(null);
            }
        BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectBusinessOpportunityInformationByBusinessId(businessFollowRecords.getBusinessId());
            if (businessOpportunityInformation.getBusinessStatusUser()!=null){
                businessFollowRecords.setBusinessStatusUser(businessOpportunityInformation.getBusinessStatusUser());
                businessFollowRecords.setStrNickName(businessOpportunityInformation.getStrNickName());
                businessFollowRecords.setStrName(businessOpportunityInformation.getStrName());
                businessFollowRecords.setBusinessStatus(businessOpportunityInformation.getBusinessStatus());
            }
            businessFollowRecords.setBusinessStatus(businessOpportunityInformation.getBusinessStatus());
        return businessFollowRecords;
    }

    /**
     * 查询商机跟进记录列表
     * 
     * @param businessFollowRecords 商机跟进记录
     * @return 商机跟进记录
     */
    @Override
    public List<BusinessFollowRecords> selectBusinessFollowRecordsList(BusinessFollowRecords businessFollowRecords)
    {
        BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectBusinessOpportunityInformationByBusinessId(businessFollowRecords.getBusinessId());
//        List<BusinessFollowRecords> followRecords=new ArrayList<>();
        List<BusinessFollowRecords> records = businessFollowRecordsMapper.selectBusinessFollowRecordsList(businessFollowRecords);
        //查询当前跟进记录的审核人等信息
        for (BusinessFollowRecords bfr:records) {
          if (Objects.nonNull(businessOpportunityInformation.getStrNickName())){
              bfr.setStrNickName(businessOpportunityInformation.getStrNickName());
          }
          if (Objects.nonNull(businessOpportunityInformation.getBusinessStatus())){
              bfr.setBusinessStatus(businessOpportunityInformation.getBusinessStatus());
          }
          if (Objects.nonNull(businessOpportunityInformation.getBusinessStatusUser())){
              bfr.setBusinessStatusUser(businessOpportunityInformation.getBusinessStatusUser());
          }
            //查询每条记录的批注人信息
            bfr.setList(businessFollowAnnotaterMapper.selectBusinessFollowAnnotaterByAnnotaterId(bfr.getRecordsId()));
        }
//        for (BusinessFollowRecords bfr:records) {
//            Long userId = SecurityUtils.getUserId();
//            if(SecurityUtils.getUserId()==bfr.getFollowId()){
//                followRecords.add(bfr);
//            }else if (StringUtils.isNotEmpty(bfr.getAnnotationsUserId())) {
//                    String[] strings = bfr.getAnnotationsUserId().split(",");
//                    for (String s : strings) {
//                        if (SecurityUtils.getUserId().toString().equals(s)) {
//                            followRecords.add(bfr);
//                        }
//                    }
//                }
//
//        }
        return records;
    }

    /**
     * 新增商机跟进记录
     * 
     * @param businessFollowRecords 商机跟进记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBusinessFollowRecords(BusinessFollowRecords businessFollowRecords)
    {
        if(StringUtils.isNotEmpty(businessFollowRecords.getArrayUserid())){
            businessFollowRecords.setAnnotationsUserId(this.getBuilder(businessFollowRecords.getArrayUserid()).toString());
        }

        //查询商机信息，添加审核人
       if (Objects.nonNull(businessFollowRecords.getBusinessStatusUser())){
           BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectBusinessOpportunityInformationByBusinessId(businessFollowRecords.getBusinessId());
           //判断是否主表存在审核人，如果不存在，则表示未提交审核
           if (Objects.isNull(businessOpportunityInformation.getBusinessStatusUser()) || businessOpportunityInformation.getBusinessStatus().equals("3")){
               businessOpportunityInformation.setBusinessStatus("2");
           }
           businessOpportunityInformation.setBusinessStatusUser(businessFollowRecords.getBusinessStatusUser());
           businessOpportunityInformation.setStrNickName(businessFollowRecords.getStrNickName());
           businessOpportunityInformation.setStrName(businessFollowRecords.getStrName());
           businessOpportunityInformationMapper.updateBusinessOpportunityInformation(businessOpportunityInformation);
       }
        businessFollowRecords.setFollowId(SecurityUtils.getUserId());
       //查询批注人，把批注人单独存储到批注人表中
        if (Objects.nonNull(businessFollowRecords.getAnnotationsUserId())){
            String[] split = businessFollowRecords.getAnnotationsUserId().split(",");
            for (String s:split){
                BusinessFollowAnnotater businessFollowAnnotater = new BusinessFollowAnnotater();
                businessFollowAnnotater.setRecordId(businessFollowRecords.getRecordsId());
                businessFollowAnnotater.setAnnotaterId(Long.parseLong(s));
                businessFollowAnnotater.setAnnotaterName(sysUserMapper.selectUserById(Long.parseLong(s)).getNickName());
                businessFollowAnnotater.setBusinessId(businessFollowRecords.getBusinessId());
                businessFollowAnnotaterMapper.insertBusinessFollowAnnotater(businessFollowAnnotater);
            }
        }
        return businessFollowRecordsMapper.insertBusinessFollowRecords(businessFollowRecords);
    }

    /**
     * 修改商机跟进记录
     * 
     * @param businessFollowRecords 商机跟进记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBusinessFollowRecords(BusinessFollowRecords businessFollowRecords)
    {
        if(StringUtils.isNotEmpty(businessFollowRecords.getArrayUserid())){
            businessFollowRecords.setAnnotationsUserId(this.getBuilder(businessFollowRecords.getArrayUserid()).toString());
        }
        //查询批注人，把批注人单独存储到批注人表中
        //删除改跟进的原有批注人信息
        businessFollowAnnotaterMapper.deleteBusinessFollowAnnotaterByRecordId(businessFollowRecords.getRecordsId());
       if (Objects.nonNull(businessFollowRecords.getAnnotationsUserId())){
           String[] split = businessFollowRecords.getAnnotationsUserId().split(",");
           for (String s:split){
               BusinessFollowAnnotater businessFollowAnnotater = new BusinessFollowAnnotater();
               businessFollowAnnotater.setRecordId(businessFollowRecords.getRecordsId());
               businessFollowAnnotater.setAnnotaterId(Long.parseLong(s));
               businessFollowAnnotater.setAnnotaterName(sysUserMapper.selectUserById(Long.parseLong(s)).getNickName());
               businessFollowAnnotater.setBusinessId(businessFollowRecords.getBusinessId());
               businessFollowAnnotaterMapper.insertBusinessFollowAnnotater(businessFollowAnnotater);
           }
       }
        //查询商机信息，修改审核人
        if (Objects.nonNull(businessFollowRecords.getBusinessStatusUser())){
            BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectBusinessOpportunityInformationByBusinessId(businessFollowRecords.getBusinessId());
            businessOpportunityInformation.setBusinessStatusUser(businessFollowRecords.getBusinessStatusUser());
            businessOpportunityInformation.setStrNickName(businessFollowRecords.getStrNickName());
            businessOpportunityInformation.setStrName(businessFollowRecords.getStrName());
            businessOpportunityInformationMapper.updateBusinessOpportunityInformation(businessOpportunityInformation);
        }
        return businessFollowRecordsMapper.updateBusinessFollowRecords(businessFollowRecords);
    }

    /**
     * 批量删除商机跟进记录
     * 
     * @param recordsIds 需要删除的商机跟进记录主键
     * @return 结果
     */
    @Override
    public int deleteBusinessFollowRecordsByRecordsIds(String[] recordsIds)
    {
        //批注人也进行删除
        for (String recordsId : recordsIds) {
            businessFollowAnnotaterMapper.deleteBusinessFollowAnnotaterByRecordId(recordsId);
        }
        return businessFollowRecordsMapper.deleteBusinessFollowRecordsByRecordsIds(recordsIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBusinessFollowRecordsByRecordsId(String recordsId) {
        //删除这条跟进记录的批注人信息
        businessFollowAnnotaterMapper.deleteBusinessFollowAnnotaterByRecordId(recordsId);
        return businessFollowRecordsMapper.deleteBusinessFollowRecordsByRecordsId(recordsId);
    }

    @Override
    public int updateBusinessFollowRecordsRemark(BusinessFollowRecords businessFollowRecords) {
        if(StringUtils.isNotEmpty(businessFollowRecords.getArrayUserid())){
            businessFollowRecords.setAnnotationsUserId(this.getBuilder(businessFollowRecords.getArrayUserid()).toString());
        }
        if(StringUtils.isNotEmpty(businessFollowRecords.getAnnotations())){
            BusinessFollowAnnotater businessFollowAnnotater=businessFollowAnnotaterMapper.selectBusinessFollowRecordsByRecordsIdAndUserId(businessFollowRecords.getRecordsId(),SecurityUtils.getUserId());
            businessFollowAnnotater.setAnnotaterDetail(businessFollowRecords.getAnnotations());
            int i = businessFollowAnnotaterMapper.updateBusinessFollowAnnotater(businessFollowAnnotater);
            return i;
        }else {
            return 0;
        }
    }

    @Override
    public int getRemarkByRecordsId(String businessId) {
        //根据id查询当前商机是否审核，审核后返回1，未审核返回0
        BusinessOpportunityInformation businessOpportunityInformation = businessOpportunityInformationMapper.selectBusinessOpportunityInformationByBusinessId(businessId);
        if (businessOpportunityInformation.getBusinessStatus().equals("1")){
            //说明通过审核
            return 0;

        }
        return 0;
    }

    /**
     * 删除商机跟进记录信息
     *
     * @return 结果
     */



    private StringBuilder getBuilder(String[] arrayUserid){
        StringBuilder str=new StringBuilder();
        for (String s:arrayUserid){
            str.append(s).append(",");
        }
        return str.deleteCharAt(str.length()-1);
    }
}
